/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.google.common.collect.Lists;
import com.iwindplus.boot.domain.constant.CommonConstant;
import com.iwindplus.boot.domain.constant.CommonConstant.ExceptionConstant;
import com.iwindplus.boot.domain.constant.CommonConstant.FileConstant;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.net.URIBuilder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

/**
 * HttpClient工具类.
 *
 * @author zengdegui
 * @since 2021/11/23
 */
@Slf4j
public class HttpClientUtil {

    private HttpClientUtil() {
        throw new IllegalStateException(CommonConstant.UTILITY_CLASS);
    }

    /**
     * get请求（参数拼接）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @return ClassicHttpRequest
     */
    public static ClassicHttpRequest get(String url, Map<String, String> header, Map<String, Object> param) {
        final URI uri = HttpClientUtil.buildQueryParameter(url, param);
        header = HttpClientUtil.buildDefaultContentType(header, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        BasicHeader[] headers = HttpClientUtil.buildHeader(header);
        HttpGet request = new HttpGet(uri);
        request.setHeaders(headers);
        return request;
    }

    /**
     * post请求（FormBody表单）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @return ClassicHttpRequest
     */
    public static ClassicHttpRequest postFormBodyRequest(String url, Map<String, String> header, Map<String, Object> param) {
        header = HttpClientUtil.buildDefaultContentType(header, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        BasicHeader[] headers = HttpClientUtil.buildHeader(header);
        HttpPost request = new HttpPost(url);
        request.setHeaders(headers);
        final UrlEncodedFormEntity formEntity = HttpClientUtil.buildFormBody(param);
        request.setEntity(formEntity);
        return request;
    }

    /**
     * post请求（MultipartBody表单）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @param files  文件集合（可选）
     * @return ClassicHttpRequest
     */
    public static ClassicHttpRequest postMultipartBodyRequest(String url, Map<String, String> header,
        Map<String, Object> param, List<MultipartFile> files) {
        header = HttpClientUtil.buildDefaultContentType(header, MediaType.MULTIPART_FORM_DATA_VALUE);
        BasicHeader[] headers = HttpClientUtil.buildHeader(header);
        HttpPost request = new HttpPost(url);
        request.setHeaders(headers);
        final MultipartEntityBuilder builder = HttpClientUtil.buildMultipartBody(param, files);
        request.setEntity(builder.build());
        return request;
    }

    /**
     * post请求（json）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param json   参数（必填）
     * @return ClassicHttpRequest
     */
    public static ClassicHttpRequest postJsonRequest(String url, Map<String, String> header, String json) {
        header = HttpClientUtil.buildDefaultContentType(header, MediaType.APPLICATION_JSON_VALUE);
        BasicHeader[] headers = HttpClientUtil.buildHeader(header);
        HttpPost request = new HttpPost(url);
        request.setHeaders(headers);
        request.setEntity(new StringEntity(json));
        return request;
    }

    /**
     * put请求（FormBody表单）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @return ClassicHttpRequest
     */
    public static ClassicHttpRequest putFormBodyRequest(String url, Map<String, String> header, Map<String, Object> param) {
        header = HttpClientUtil.buildDefaultContentType(header, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        BasicHeader[] headers = HttpClientUtil.buildHeader(header);
        HttpPut request = new HttpPut(url);
        request.setHeaders(headers);
        final UrlEncodedFormEntity builder = HttpClientUtil.buildFormBody(param);
        request.setEntity(builder);
        return request;
    }

    /**
     * put请求（MultipartBody表单）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @param files  文件集合（可选）
     * @return ClassicHttpRequest
     */
    public static ClassicHttpRequest putMultipartBodyRequest(String url, Map<String, String> header,
        Map<String, Object> param, List<MultipartFile> files) {
        header = HttpClientUtil.buildDefaultContentType(header, MediaType.MULTIPART_FORM_DATA_VALUE);
        BasicHeader[] headers = HttpClientUtil.buildHeader(header);
        HttpPut request = new HttpPut(url);
        request.setHeaders(headers);
        final MultipartEntityBuilder builder = HttpClientUtil.buildMultipartBody(param, files);
        request.setEntity(builder.build());
        return request;
    }

    /**
     * put请求（json）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param json   参数（必填）
     * @return ClassicHttpRequest
     */
    public static ClassicHttpRequest putJsonRequest(String url, Map<String, String> header, String json) {
        header = HttpClientUtil.buildDefaultContentType(header, MediaType.APPLICATION_JSON_VALUE);
        BasicHeader[] headers = HttpClientUtil.buildHeader(header);
        HttpPut request = new HttpPut(url);
        request.setHeaders(headers);
        request.setEntity(new StringEntity(json));
        return request;
    }

    /**
     * delete请求（参数拼接）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @return ClassicHttpRequest
     */
    public static ClassicHttpRequest delete(String url, Map<String, String> header, Map<String, Object> param) {
        header = HttpClientUtil.buildDefaultContentType(header, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        final URI uri = HttpClientUtil.buildQueryParameter(url, param);
        HttpDelete request = new HttpDelete(uri);
        BasicHeader[] headers = HttpClientUtil.buildHeader(header);
        request.setHeaders(headers);
        return request;
    }

    /**
     * delete请求（FormBody表单）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param param  参数（可选）
     * @return ClassicHttpRequest
     */
    public static ClassicHttpRequest deleteFormBodyRequest(String url, Map<String, String> header, Map<String, Object> param) {
        header = HttpClientUtil.buildDefaultContentType(header, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        BasicHeader[] headers = HttpClientUtil.buildHeader(header);
        HttpDelete request = new HttpDelete(url);
        request.setHeaders(headers);
        final UrlEncodedFormEntity builder = HttpClientUtil.buildFormBody(param);
        request.setEntity(builder);
        return request;
    }

    /**
     * delete请求（json）.
     *
     * @param url    路径（必填）
     * @param header 请求头（可选）
     * @param json   参数（必填）
     * @return ClassicHttpRequest
     */
    public static ClassicHttpRequest deleteJsonRequest(String url, Map<String, String> header, String json) {
        header = HttpClientUtil.buildDefaultContentType(header, MediaType.APPLICATION_JSON_VALUE);
        BasicHeader[] headers = HttpClientUtil.buildHeader(header);
        HttpDelete request = new HttpDelete(url);
        request.setHeaders(headers);
        request.setEntity(new StringEntity(json));
        return request;
    }

    /**
     * 执行同步请求，同步响应结果.
     *
     * @param httpClient http客户端（必填）
     * @param request    请求（必填）
     * @return String
     */
    public static String executeRequest(CloseableHttpClient httpClient, ClassicHttpRequest request) {
        HttpClientResponseHandler<String> responseHandler = classicHttpResponse -> {
            final HttpEntity entity = classicHttpResponse.getEntity();
            if (Objects.nonNull(entity)) {
                return EntityUtils.toString(entity);
            }
            return null;
        };
        try {
            return httpClient.execute(request, responseHandler);
        } catch (IOException ex) {
            log.error(ExceptionConstant.IO_EXCEPTION, ex);
        } finally {
            HttpClientUtil.closeHttpClient(httpClient);
        }
        return null;
    }

    /**
     * 关闭Response.
     *
     * @param httpClient httpClient
     */
    public static void closeHttpClient(CloseableHttpClient httpClient) {
        if (Objects.isNull(httpClient)) {
            return;
        }
        try {
            httpClient.close();
        } catch (Exception ex) {
            log.error(ExceptionConstant.EXCEPTION, ex);
        }
    }

    /**
     * 构造请求头.
     *
     * @param header 请求头
     * @return BasicHeader[]
     */
    private static BasicHeader[] buildHeader(Map<String, String> header) {
        if (MapUtil.isEmpty(header)) {
            return new BasicHeader[0];
        }
        BasicHeader[] headers = new BasicHeader[header.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : header.entrySet()) {
            headers[i++] = new BasicHeader(entry.getKey(), entry.getValue());
        }
        return headers;
    }

    private static Map<String, String> buildDefaultContentType(Map<String, String> header, String contentType) {
        if (MapUtil.isEmpty(header)) {
            header = new HashMap<>(16);
        }
        if (CharSequenceUtil.isBlank(header.get(HttpHeaders.CONTENT_TYPE))) {
            header.put(HttpHeaders.CONTENT_TYPE, contentType);
        }
        return header;
    }

    private static URI buildQueryParameter(String url, Map<String, Object> param) {
        URI uri = null;
        URIBuilder builder = new URIBuilder(URI.create(url));
        if (MapUtil.isNotEmpty(param)) {
            for (Map.Entry<String, Object> entry : param.entrySet()) {
                final Object value = entry.getValue();
                builder.addParameter(entry.getKey(), Objects.nonNull(value) ? value.toString() : null);
            }
        }
        try {
            uri = builder.build();
        } catch (URISyntaxException ex) {
            log.error(ExceptionConstant.URI_SYNTAX_EXCEPTION, ex);
        }
        return uri;
    }

    private static UrlEncodedFormEntity buildFormBody(Map<String, Object> param) {
        List<BasicNameValuePair> parameters = Lists.newArrayList();
        for (Map.Entry<String, Object> entry : param.entrySet()) {
            final Object value = entry.getValue();
            parameters.add(new BasicNameValuePair(entry.getKey(), Objects.nonNull(value) ? value.toString() : null));
        }
        return new UrlEncodedFormEntity(parameters, Charset.defaultCharset());
    }

    private static MultipartEntityBuilder buildMultipartBody(Map<String, Object> param, List<MultipartFile> multipartFiles) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(Charset.defaultCharset());
        builder.setMode(HttpMultipartMode.LEGACY);
        if (MapUtil.isNotEmpty(param)) {
            for (Map.Entry<String, Object> entry : param.entrySet()) {
                final Object value = entry.getValue();
                builder.addTextBody(entry.getKey(), Objects.nonNull(value) ? value.toString() : null);
            }
        }
        if (CollUtil.isNotEmpty(multipartFiles)) {
            for (MultipartFile file : multipartFiles) {
                builder.addBinaryBody(FileConstant.FILE, FilesUtil.getBytes(file), ContentType.DEFAULT_BINARY, file.getOriginalFilename());
            }
        }
        return builder;
    }
}
